package com.example.dish.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.common.Result;
import com.example.dish.service.CategoryService;
import com.example.dish.service.DishFlavorService;
import com.example.dish.service.DishService;
import com.example.dish_model.dto.DishDTO;
import com.example.dish_model.entity.Category;
import com.example.dish_model.entity.Dish;
import com.example.dish_model.entity.DishFlavor;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜品管理 前端控制器
 * </p>
 *
 * @author sjz
 * @since 2024-06-30
 */
@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {

    @Resource
    private DishService dishService;

    @Resource
    private CategoryService categoryService;

    @Resource
    private DishFlavorService dishFlavorService;


    /**
     * 新增菜品
     *
     * @param dishDTO
     * @return
     */
    @PostMapping
    public Result<String> add(@RequestBody DishDTO dishDTO) {
        log.info(dishDTO.toString());
        dishService.saveDishAndFlavors(dishDTO);
        return Result.success("添加成功");
    }


    /**
     * 分页查询菜品信息
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public Result<Page<DishDTO>> getPage(long page, long pageSize, String name) {
        Page<DishDTO> dishDTOPage = dishService.getPage(page, pageSize, name);
        return Result.success(dishDTOPage);
    }

    /**
     * 根据id查询菜品信息
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result<DishDTO> getById(@PathVariable("id") String id) {
        DishDTO dishDTO = dishService.getDishAndFlavorsById(id);
        return Result.success(dishDTO);
    }

    /**
     * 修改菜品信息
     *
     * @param dishDTO
     * @return
     */
    @PutMapping
    public Result<String> update(@RequestBody DishDTO dishDTO) {

        dishService.updateDishAndFlavors(dishDTO);
        return Result.success("修改菜品信息成功");
    }

    /**
     * 修改售卖状态,可以批量修改
     *
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    public Result<String> updateStatus(@PathVariable("status") int status, @RequestParam List<String> ids) {

        log.info("ids:{}", ids);
        log.info("status:{}", status);

        //根据传入的ids,查询数据库
        List<Dish> dishList = dishService.getByIds(ids);
        //判断当前点击的是停售按钮还是启售按钮
        if (status == 0) {
            //当前点击的是停售按钮
            for (Dish dish : dishList) {
                //修改状态为停售
                dish.setStatus(0);
                dishService.updateById(dish);
            }
        } else {
            //当前点击的是启售按钮
            for (Dish dish : dishList) {
                //修改状态为启售
                dish.setStatus(1);
                dishService.updateById(dish);
            }
        }
        return Result.success("修改成功");

    }


    /**
     * 删除菜品信息,可以批量删除
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    public Result<String> delete(@RequestParam List<String> ids) {
        String result = dishService.removeDish(ids);
        return Result.success(result);
    }

    /**
     * 新建套餐处根据分类id查询菜品数据
     *
     * @param dish
     * @return
     */
//    @GetMapping("/list")
//    public Result<List<Dish>> list(Dish dish) {
//        //构建查询条件
//        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
//        wrapper.eq(dish != null, Dish::getCategoryId, dish.getCategoryId());
//        return Result.success(dishService.list(wrapper));
//    }
    @GetMapping("/list")
    public Result<List<DishDTO>> list(Dish dish) {
        List<DishDTO> dishDtoList = null;

        //构造查询条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<Dish>();
        queryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        // 添加条件，查询状态为1（起售状态）的菜品
        queryWrapper.eq(Dish::getStatus, 1);
        //添加排序条件
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(queryWrapper);

        dishDtoList = list.stream().map(item -> {
            DishDTO dishDTO = new DishDTO();
            BeanUtils.copyProperties(item, dishDTO);
            String categoryId = item.getCategoryId();//分类id
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                String categoryName = category.getName();
                dishDTO.setCategoryName(categoryName);
            }
            String dishID = item.getId();//当前菜品id
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DishFlavor::getDishId, dishID);
            List<DishFlavor> dishFlavorList = dishFlavorService.list(lambdaQueryWrapper);
            dishDTO.setFlavors(dishFlavorList);

            return dishDTO;
        }).collect(Collectors.toList());


        return Result.success(dishDtoList);
    }
}
